package com.ecoolex.ying.space.core.manager;

import com.ecoolex.framework.common.enums.ResultCode;
import com.ecoolex.framework.common.pojo.Page;
import com.ecoolex.framework.common.pojo.Pagination;
import com.ecoolex.framework.common.util.BizAssert;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.ying.space.core.dao.UserWorksMarktingDAO;
import com.ecoolex.ying.space.entity.UserWorksMarkting;
import com.ecoolex.ying.space.entity.UserWorksMarkting.Column;
import com.ecoolex.ying.space.entity.UserWorksMarktingExample;
import com.ecoolex.ying.space.entity.UserWorksMarktingExample.Criteria;

import java.time.Instant;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserWorksMarktingManager {
	
    @Autowired
    private UserWorksMarktingDAO dao;
    
    public UserWorksMarkting get(Integer marktingId) {
		return dao.selectByPrimaryKeyWithLogicalDelete(marktingId, UserWorksMarkting.NOT_DELETED);
	}

	public Pagination<UserWorksMarkting> query(Page page) {
		UserWorksMarktingExample example = new UserWorksMarktingExample();
		Criteria criteria = example.createCriteria();
		criteria.andDeletedEqualTo(UserWorksMarkting.NOT_DELETED);
		example.setOffset(page.getFirstIndex());
		example.setRows(page.getPageSize());
		example.orderBy(Column.weight.desc());
		return Pagination.create(page, 
			dao.countByExample(example),
			() -> dao.selectByExample(example));
	}
	
	private void verify(UserWorksMarkting record) {
		BizAssert.isTrue(Check.notNullOrEmpty(record.getPositionName()),ResultCode.VERIFY.build(10), "位置名称为空");
		BizAssert.isTrue(Check.notNull(record.getWeight()),ResultCode.VERIFY.build(11), "权重位空");
	}

	public UserWorksMarkting add(UserWorksMarkting record, String createUser){
		verify(record);
		record.setDeleted(UserWorksMarkting.NOT_DELETED);
		record.setCreateUser(createUser);
		record.setCreateTime(Date.from(Instant.now()));
		record.setUpdateUser(createUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.insert(record);
		return record;
	}

	public UserWorksMarkting edit(UserWorksMarkting record, String updateUser){
		verify(record);
		record.setUpdateUser(updateUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.updateByPrimaryKeySelective(record, Column.excludes(Column.createUser,Column.createTime,Column.deleted));
		return record;
	}

	public void deleteMarkting(UserWorksMarkting record, String updateUser){
		record.setDeleted(UserWorksMarkting.IS_DELETED);
		record.setUpdateUser(updateUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.updateByPrimaryKeySelective(record,Column.updateUser,Column.updateTime,Column.deleted);
	}
}